package cn.szzsi.service;

import cn.szzsi.common.bean.dto.TemplateObj;
import cn.szzsi.common.bean.dto.WxTemplate;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.Tocash;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2016/12/12.
 */
public class UserService {
    public static final UserService us = new UserService();
    public static final String TEMP_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
    //向所有父级发送会员关注模板消息
    public void sendFocusMSG(String apiid, String touser, Member m){
        //获取token
        String token = AccessTokenApi.getAccessToken().getAccessToken();
        //发送消息
        Member toUserMember = Member.dao.findById(touser);
        if(toUserMember!=null && StrKit.notBlank(toUserMember.getStr("openid")) && m!=null){
            String result = HttpKit.post(String.format(TEMP_MSG_URL,token), getFocusJson(toUserMember.getStr("openid"),m));
            JSONObject userJson=new JSONObject(result);
            if (null != userJson) {
                if (0 != userJson.getInt("errcode")) {
                    System.out.println("错误 errcode:"+userJson.getInt("errcode")+" errmsg:"+ userJson.getString("errmsg"));
                }
            }
        }
    }


    public BigDecimal getRealRewards(Member member, String shopId){
        /*String expectSql="select sum(backmoney)totaIncome from(\n" +
                "SELECT  IFNULL(sum(money),0)backmoney FROM `mall_backmoney` where uid='"+member.getStr("id")+"' and type = 'FX' \n" +
                "UNION ALL\n" +
                "SELECT  IFNULL(sum(profit),0)backmoney FROM `b_customer_dividend` where mid='"+member.getStr("id")+"' \n" +
                "UNION ALL \n" +
                "SELECT IFNULL(sum(profit),0)backmoney FROM `b_customer_allowance` where mid='"+member.getStr("id")+"' \n" +
                ")as totaIncome";*/
        //String expectSql="SELECT IFNULL(sum(addMoney),0)totaIncome FROM `mall_user_balance_detail` where mid='"+member.getStr("id")+"' and (type='0' or (type='1' and status=1) or type='2' or type='7')";
        String expectSql="select balance from mall_user_balance where mid='"+member.getStr("id")+"'";
        BigDecimal totalProfit = Db.queryColumn(expectSql);
        totalProfit=totalProfit.setScale(0, BigDecimal.ROUND_DOWN);//保留整数部分
        //BigDecimal totalProfit = Db.queryColumn("select sum(money) from mall_backmoney where uid = ? and type = 'FX'",member.getStr("id"));
        //BigDecimal totalOutProfit = Db.queryColumn("select sum(cashAmount) from mall_tocash where uid = ? and member_id = ? and status = 0",shopId,member.get("id"));
        //if(totalOutProfit==null)
        //totalOutProfit = new BigDecimal(0);
        if(totalProfit==null){
            totalProfit = new BigDecimal(0);
        }
        if(totalProfit.compareTo(new BigDecimal(0))<0){
            totalProfit = new BigDecimal(0);
        }
        return totalProfit;
        //return totalProfit.subtract(totalOutProfit);
    }

    /**
     * 发送提现提醒消息
     * @param member
     * @param cashAmount
     */
    public void sendToCashingMsg(Member member, BigDecimal cashAmount){
        ApiResult result = TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(member.getStr("openid"))
                // 模板id
                .setTemplate_id("HyQguM4a4HZxq8ppp16E0csVr6weyQgDRz9hszy4Hog")
                .setTopcolor("#eb414a")
//                .setUrl("https://m.xxxx.cn/qrcode/t/xxxxxx")

                // 模板参数
                .add("first", "您的提现成功啦", "#999")
                .add("keyword1", cashAmount.toString()+"元", "#999")
                .add("keyword2", DateFormatUtils.format(DateUtils.addDays(new Date(),1),"yyyy-MM-dd HH:mm:ss"), "#999")
                .add("remark", "感谢您的使用", "#999")
                .build());
    }
    /**
     * 发送提现失败提醒消息
     * @param member
     * @param toCashing
     */
    public void sendToCashingFailMsg(Member member, Tocash toCashing){
        TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(member.getStr("openid"))
                // 模板id
                .setTemplate_id("XOpNf6h1PCgVgPJ8i2iDZ61n7ol6Eon-9EJPu8XHyS0")
                .setTopcolor("#eb414a")
//                .setUrl("https://m.xxxx.cn/qrcode/t/xxxxxx")

                // 模板参数
                .add("first", "您的提现申请已处理", "#999")
                .add("keyword1", toCashing.getBigDecimal("cashAmount")+"元", "#999")
                .add("keyword2", "提现到银行卡", "#999")
                .add("keyword3", DateFormatUtils.format(toCashing.getDate("createDate"),"yyyy-MM-dd HH:mm:ss"), "#999")
                .add("keyword4", "审核不通过，原因："+(StrKit.isBlank(toCashing.getStr("reason"))?"无":toCashing.getStr("reason")), "#999")
                .add("keyword5", DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"), "#999")
                .add("remark", "如有任何疑问，请联系我们的客服，客服电话：0374-2627333。", "#999")
                .build());
    }


    /**
     * 发送提现成功消息
     * @param member
     * @param cashAmount
     */
    public void sendToCashingSucessMsg(Member member, String cashAmount, String bank){
        TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(member.getStr("openid"))
                // 模板id
                .setTemplate_id("muTqKMMk6krNA5D3eGBW_eMN8JlI9AQy30xNCpEhATw")
                .setTopcolor("#eb414a")
//                .setUrl("https://m.xxxx.cn/qrcode/t/xxxxxx")

                // 模板参数
                .add("first", "亲，您好！您提交了提现申请", "#999")
                .add("keyword1", cashAmount+"元", "#999")
                .add("keyword2", bank, "#999")
                .add("keyword3", DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"), "#999")
                .add("keyword4", DateFormatUtils.format(DateUtils.addDays(new Date(),1),"yyyy-MM-dd HH:mm:ss"), "#999")
                .add("remark", "我们会在1到3个工作日处理，请耐心等待。", "#999")
                .build());
    }

    //向所有父级发送会员分成模板消息
    public void sendFxMSG(String apiid, String id, Orders orders, String money){
        //获取token
        String token = AccessTokenApi.getAccessToken().getAccessToken();
        //发送消息
        Member m = Member.dao.findById(id);
        if(m == null || orders == null)
            return ;
        String result = HttpKit.post(String.format(TEMP_MSG_URL,token), getOrderFxJson(orders,m.getStr("openid"),money));
        JSONObject userJson=new JSONObject(result);
        if (null != userJson) {
            if (0 != userJson.getInt("errcode")) {
                System.out.println("错误 errcode:"+userJson.getInt("errcode")+" errmsg:"+ userJson.getString("errmsg"));
            }
        }
        System.out.println("模板消息发送结果："+result);
    }

    public String getOrderFxJson(Orders orders, String openid, String money){
        WxTemplate temp = new WxTemplate();
        temp.setTouser(openid);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("bevMeCz7QVmQnaKuTfvuHGkrfcOsiS4QDoLkV8CGa5c");
        Map<String,TemplateObj> m = new HashMap<String,TemplateObj>();

        TemplateObj first = new TemplateObj();
        first.setColor("#000000");
        first.setValue("亲，您又成功分销出一笔订单了");
        m.put("first", first);

        TemplateObj keyword1 = new TemplateObj();
        keyword1.setColor("#000000");
        keyword1.setValue(orders.getStr("orderSn"));
        m.put("keyword1", keyword1);

        TemplateObj keyword2 = new TemplateObj();
        keyword2.setColor("#000000");
        keyword2.setValue(orders.getBigDecimal("totalAmount").toString());
        m.put("keyword2", keyword2);

        TemplateObj keyword3 = new TemplateObj();
        keyword3.setColor("#000000");
        keyword3.setValue(money);
        m.put("keyword3", keyword3);

        TemplateObj keyword4 = new TemplateObj();
        keyword4.setColor("#000000");
        keyword4.setValue(DateFormatUtils.format(new Date(),"yyyy/MM/dd HH:mm"));
        m.put("keyword4", keyword4);

        TemplateObj remark = new TemplateObj();
        remark.setColor("#000000");
        remark.setValue("开元一通感谢有你！");
        m.put("remark", remark);

        temp.setData(m);

        return JsonKit.toJson(temp);
    }


    public String getFocusJson(String touser, Member member){
        WxTemplate temp = new WxTemplate();
//        temp.setUrl("https://weixin.qq.com/download");
        temp.setTouser(touser);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("RlZoYWu7bPAgVTeVl__OOLzJjpj2UplRhFwZiBR6LLI");
        Map<String,TemplateObj> m = new HashMap<String,TemplateObj>();

        TemplateObj first = new TemplateObj();
        first.setColor("#000000");
        first.setValue("您的开元一通商城有新会员加入");
        m.put("first", first);

        TemplateObj keyword1 = new TemplateObj();
        keyword1.setColor("#000000");
        keyword1.setValue(member.getStr("username"));
        m.put("keyword1", keyword1);

        TemplateObj keyword2 = new TemplateObj();
        keyword2.setColor("#000000");
        keyword2.setValue(member.getStr("code"));
        m.put("keyword2", keyword2);

        TemplateObj keyword3 = new TemplateObj();
        keyword3.setColor("#000000");
        keyword3.setValue(DateFormatUtils.format(new Date(),"yyyy/MM/dd HH:mm"));
        m.put("keyword3", keyword3);

        TemplateObj remark = new TemplateObj();
        remark.setColor("#000000");
        remark.setValue("付出必有回报，亲，加油哦，开元一通感谢有您！");
        m.put("remark", remark);

        temp.setData(m);

        return JsonKit.toJson(temp);
    }


}
